# -*- coding: utf-8 -*-
"""Jenkins任务管理器"""
from typing import Dict, Optional
from flask import current_app
import time


class JenkinsJobManager:
    """Jenkins任务管理器，负责处理Jenkins相关操作"""

    def __init__(self, app=None):
        self.app = app
        self.job_name = None
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        """初始化应用"""
        self.app = app
        self.job_name = app.config['JENKINS_JOB_NAME']

    def get_build_status(self, build_number: int) -> Optional[str]:
        """获取构建状态"""
        max_retries = 3
        retry_count = 0
        
        while retry_count < max_retries:
            try:
                from app.services.job_service import JobService
                job_service = JobService()
                return job_service.jenkins_client.get_build_status(
                    job_name=self.job_name,
                    build_number=build_number
                )
            except Exception as e:
                retry_count += 1
                current_app.logger.error(f"获取构建状态失败 (尝试 {retry_count}/{max_retries}): {str(e)}")
                if retry_count < max_retries:
                    time.sleep(2)  # 等待2秒后重试
                else:
                    return None

    def execute_job(self, strategy: Dict, device_name: str) -> Dict:
        """执行Jenkins任务"""
        max_retries = 3
        retry_count = 0
        
        while retry_count < max_retries:
            try:
                from app.services.job_service import JobService
                job_service = JobService()
                result = job_service.execute_job(strategy, device_name)
                
                if result.get('status') == 'success':
                    current_app.logger.info(
                        f"设备 {device_name} 启动新构建 "
                        f"#{result.get('build_number')}"
                    )
                    return result
                else:
                    retry_count += 1
                    current_app.logger.error(
                        f"设备 {device_name} 启动构建失败 (尝试 {retry_count}/{max_retries}): "
                        f"{result.get('message', '未知错误')}"
                    )
                    if retry_count < max_retries:
                        time.sleep(2)  # 等待2秒后重试
                    else:
                        return result
                    
            except Exception as e:
                retry_count += 1
                current_app.logger.error(
                    f"执行Jenkins任务失败 (尝试 {retry_count}/{max_retries}): {str(e)}"
                )
                if retry_count < max_retries:
                    time.sleep(2)  # 等待2秒后重试
                else:
                    return {'status': 'error', 'message': str(e)} 